package com.shk.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.aliyuncs.exceptions.ClientException;
import com.shk.constant.MessageConstant;
import com.shk.constant.RedisMessageConstant;
import com.shk.entity.Result;
import com.shk.pojo.Order;
import com.shk.service.OrderService;
import com.shk.utils.SMSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderController {
@Autowired private JedisPool jedisPool;

@Reference
        private OrderService orderService;
    @RequestMapping("/sunmit")
    public Result sunbit(@RequestBody Map map){
        /*从redis中取存放的验证码 与页面穿过来的验证码进行对比
        * 判断手机号
        * 身份证号
        * 调用service
        * 设置预约类型
        * 成功后发送短信提醒用户
        * 失败返回失败信息*/

        String validateCode =(String) map.get("validateCode");
        String telephone = (String) map.get("telephone");
        String idCard = (String) map.get("idCard");
        String Code = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_ORDER);

        if(validateCode==null && Code==null && !validateCode.equals(Code)){
            return new Result(false, MessageConstant.TELEPHONE_VALIDATECODE_NOTNULL);
        }

        if(telephone==null){
            return new Result(false, MessageConstant.TELEPHONE_VALIDATECODE_NOTNULL);
        }

        if(idCard==null){
            return new Result(false, "身份证号不可以为空");
        }

        map.put("orderType",Order.ORDERTYPE_WEIXIN);
        Result result=null;
        try {
             result=orderService.submit(map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(result.isFlag()){
            try {
                SMSUtils.sendShortMessage(SMSUtils.ORDER_NOTICE,telephone,(String)map.get("orderDate"));
            } catch (ClientException e) {
                e.printStackTrace();
            }
            return result;
        }
        return result;
    }

    @RequestMapping("/findById")
    public Result findById(Integer id){
        try {
            Map map=  orderService.findById(id);
            return new Result(true,MessageConstant.QUERY_ORDER_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_ORDER_FAIL);
        }

    }

}
